package com.farm.wcp.util;

import org.apache.commons.lang.StringUtils;

import com.farm.parameter.FarmParameterService;
import com.farm.util.cache.FarmCacheName;
import com.farm.util.cache.FarmCaches;


public class PasswordChecks {
	
	public static void check(String loginname, String ip) {
		int loginnameFailNum = FarmParameterService.getInstance()
				.getParameterInt("config.sys.password.loginfail.loginname.maxnum");
		int ipFailNum = FarmParameterService.getInstance().getParameterInt("config.sys.password.loginfail.ip.maxnum");

		if (loginnameFailNum > 0 && StringUtils.isNotBlank(loginname)) {
			Integer cnum = (Integer) FarmCaches.getInstance().getCacheData(loginname, FarmCacheName.farm_login_fail);
			if (cnum != null && cnum > loginnameFailNum) {
				throw new RuntimeException("登录失败次数太多，请" + getCacheLiveTime() + "分钟后再尝试!"); // TODO: handle exception
			}
		}
		if (ipFailNum > 0 && StringUtils.isNotBlank(ip)) {
			Integer cnum = (Integer) FarmCaches.getInstance().getCacheData(ip, FarmCacheName.farm_login_fail);
			if (cnum != null && cnum > ipFailNum) {
				throw new RuntimeException("登录失败次数太多，请" + getCacheLiveTime() + "分钟后再尝试!");
			}
		}
	}

	private static long getCacheLiveTime() {
		long minute = 0;
		try {
			minute = (long) Math
					.ceil(Double.valueOf(FarmCaches.getInstance().getliveTime(FarmCacheName.farm_login_fail)) / 60);
		} catch (Exception e) {
			minute = FarmCaches.getInstance().getliveTime(FarmCacheName.farm_login_fail);
		}
		return minute;
	}

	
	public static void addFail(String loginname, String ip) {
		if (FarmParameterService.getInstance().getParameterInt("config.sys.password.loginfail.loginname.maxnum") > 0
				&& StringUtils.isNotBlank(loginname)) {
			Integer cnum = (Integer) FarmCaches.getInstance().getCacheData(loginname, FarmCacheName.farm_login_fail);
			if (cnum == null) {
				FarmCaches.getInstance().putCacheData(loginname, 1, FarmCacheName.farm_login_fail);
			} else {
				FarmCaches.getInstance().putCacheData(loginname, cnum + 1, FarmCacheName.farm_login_fail);
			}
		}
		if (FarmParameterService.getInstance().getParameterInt("config.sys.password.loginfail.ip.maxnum") > 0
				&& StringUtils.isNotBlank(ip)) {
			Integer cnum = (Integer) FarmCaches.getInstance().getCacheData(ip, FarmCacheName.farm_login_fail);
			if (cnum == null) {
				FarmCaches.getInstance().putCacheData(ip, 1, FarmCacheName.farm_login_fail);
			} else {
				FarmCaches.getInstance().putCacheData(ip, cnum + 1, FarmCacheName.farm_login_fail);
			}
		}
	}
}
